package br.fbv.compreja.negocio.infra;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import br.fbv.compreja.activity.base.BuzzException;

public class DataBaseHelper extends SQLiteOpenHelper {

	private Context context;

	public DataBaseHelper(Context context) {
		super(context, "compreja_db", null, 1);
		this.context = context;
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		try {

			BufferedReader br = new BufferedReader(new InputStreamReader(
					context.getAssets().open("setup_db.sql")));
			StringBuffer bufferSQL = new StringBuffer();
			String linha = null;
			while ((linha = br.readLine()) != null) {
				bufferSQL.append(linha);
				if (bufferSQL.indexOf(";") > 0) {
					db.execSQL(bufferSQL.toString().trim());
					bufferSQL.delete(0, bufferSQL.length());
				}
			}
			br.close();
		} catch (IOException e) {
			throw new BuzzException(
					"Problemas fazer o setup do banco de dados.", e);
		}
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// Como ainda estamos na primeira versão do DB,
		// não precisamos nos preocupar com o update agora.
	}

}
